import React, { useState } from 'react';
import { Card, Form, Input, Button, Avatar, Upload, Row, Col, message } from 'antd';
import { UserOutlined, UploadOutlined, EditOutlined, SaveOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import type { UploadFile } from 'antd/es/upload';

interface ProfileData {
  username: string;
  realName: string;
  email: string;
  phone: string;
  department: string;
  position: string;
  avatar: string;
}

const Profile: React.FC = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [editing, setEditing] = useState(false);
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  // 模拟用户数据
  const userData: ProfileData = {
    username: 'admin',
    realName: '张三',
    email: 'zhangsan@example.com',
    phone: '13800138000',
    department: '信息技术部',
    position: '系统管理员',
    avatar: ''
  };

  // 处理表单提交
  const handleSubmit = async (values: ProfileData) => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      message.success('个人信息更新成功');
      setEditing(false);
    } catch (error) {
      message.error('更新失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 处理头像上传
  const handleAvatarChange = (info: any) => {
    if (info.file.status === 'done') {
      message.success('头像上传成功');
      form.setFieldsValue({ avatar: info.file.response?.url });
    } else if (info.file.status === 'error') {
      message.error('头像上传失败');
    }
    setFileList(info.fileList);
  };

  // 上传前检查
  const beforeUpload = (file: File) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传JPG/PNG格式的图片!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过2MB!');
    }
    return isJpgOrPng && isLt2M;
  };

  return (
    <div style={{ padding: '24px' }}>
      <Card 
        title="个人中心" 
        extra={
          editing ? (
            <Button 
              type="primary" 
              icon={<SaveOutlined />}
              loading={loading}
              onClick={() => form.submit()}
            >
              保存
            </Button>
          ) : (
            <Button 
              type="primary" 
              icon={<EditOutlined />}
              onClick={() => setEditing(true)}
            >
              编辑
            </Button>
          )
        }
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={userData}
          onFinish={handleSubmit}
          disabled={!editing}
        >
          <Row gutter={24}>
            <Col span={6}>
              <Form.Item label="头像">
                <div style={{ textAlign: 'center' }}>
                  <Avatar 
                    size={120} 
                    icon={<UserOutlined />}
                    src={userData.avatar || undefined}
                    style={{ marginBottom: 16 }}
                  />
                  {editing && (
                    <Upload
                      name="avatar"
                      listType="picture-card"
                      className="avatar-uploader"
                      showUploadList={false}
                      action="/api/upload/avatar"
                      beforeUpload={beforeUpload}
                      onChange={handleAvatarChange}
                      fileList={fileList}
                    >
                      <Button icon={<UploadOutlined />}>更换头像</Button>
                    </Upload>
                  )}
                </div>
              </Form.Item>
            </Col>
            
            <Col span={18}>
              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    label="用户名"
                    name="username"
                    rules={[{ required: true, message: '请输入用户名' }]}
                  >
                    <Input placeholder="请输入用户名" />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    label="真实姓名"
                    name="realName"
                    rules={[{ required: true, message: '请输入真实姓名' }]}
                  >
                    <Input placeholder="请输入真实姓名" />
                  </Form.Item>
                </Col>
              </Row>
              
              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    label="邮箱"
                    name="email"
                    rules={[
                      { required: true, message: '请输入邮箱' },
                      { type: 'email', message: '请输入有效的邮箱地址' }
                    ]}
                  >
                    <Input placeholder="请输入邮箱" />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    label="手机号"
                    name="phone"
                    rules={[
                      { required: true, message: '请输入手机号' },
                      { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }
                    ]}
                  >
                    <Input placeholder="请输入手机号" />
                  </Form.Item>
                </Col>
              </Row>
              
              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    label="部门"
                    name="department"
                    rules={[{ required: true, message: '请输入部门' }]}
                  >
                    <Input placeholder="请输入部门" />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    label="职位"
                    name="position"
                    rules={[{ required: true, message: '请输入职位' }]}
                  >
                    <Input placeholder="请输入职位" />
                  </Form.Item>
                </Col>
              </Row>
            </Col>
          </Row>
        </Form>
      </Card>
    </div>
  );
};

export default Profile;